package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.dto.PurchaseReturnAddDTO;
import com.intelligent.dto.PurchaseReturnQueryDTO;
import com.intelligent.mapper.PurchaseOrderMapper;
import com.intelligent.mapper.PurchaseReturnMapper;
import com.intelligent.mapper.PurchaseSupplierMapper;
import com.intelligent.mapper.ProductMapper;
import com.intelligent.mapper.WarehouseMapper;
import com.intelligent.mapper.UnitMapper;
import com.intelligent.pojo.PurchaseReturn;
import com.intelligent.pojo.PurchaseOrder;
import com.intelligent.pojo.PurchaseSupplier;
import com.intelligent.pojo.Product;
import com.intelligent.pojo.Warehouse;
import com.intelligent.pojo.Unit;
import com.intelligent.service.PurchaseReturnService;
import com.intelligent.vo.PurchaseReturnVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
* @author 86188
* @description 针对表【purchase_return(采购退货表)】的数据库操作Service实现
* @createDate 2025-09-04 15:08:07
*/
@Service
public class PurchaseReturnServiceImpl extends ServiceImpl<PurchaseReturnMapper, PurchaseReturn>
    implements PurchaseReturnService{

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    @Autowired
    private PurchaseSupplierMapper purchaseSupplierMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Autowired
    private UnitMapper unitMapper;

    /**
     * 分页查询采购退货列表
     */
    @Override
    public IPage<PurchaseReturnVO> getPurchaseReturnPage(PurchaseReturnQueryDTO queryDTO) {
        // 创建分页对象
        Page<PurchaseReturn> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());

        // 构建查询条件
        LambdaQueryWrapper<PurchaseReturn> queryWrapper = new LambdaQueryWrapper<>();

        // 收集所有需要查询的ID列表
        List<Long> orderIds = new ArrayList<>();
        List<Long> supplierIds = new ArrayList<>();
        List<Long> productIds = new ArrayList<>();

        // 根据采购需求单号模糊查询（通过采购订单关联）
        if (StringUtils.hasText(queryDTO.getDemandOrderNo())) {
            LambdaQueryWrapper<PurchaseOrder> orderWrapper = new LambdaQueryWrapper<>();
            orderWrapper.like(PurchaseOrder::getOrderNo, queryDTO.getDemandOrderNo());
            List<PurchaseOrder> orders = purchaseOrderMapper.selectList(orderWrapper);
            orderIds.addAll(orders.stream().map(PurchaseOrder::getId).collect(Collectors.toList()));
        }

        // 根据采购订单编号模糊查询
        if (StringUtils.hasText(queryDTO.getPurchaseOrderNo())) {
            LambdaQueryWrapper<PurchaseOrder> orderWrapper = new LambdaQueryWrapper<>();
            orderWrapper.like(PurchaseOrder::getOrderNo, queryDTO.getPurchaseOrderNo());
            List<PurchaseOrder> orders = purchaseOrderMapper.selectList(orderWrapper);
            orderIds.addAll(orders.stream().map(PurchaseOrder::getId).collect(Collectors.toList()));
        }

        // 根据供应商编号模糊查询
        if (StringUtils.hasText(queryDTO.getSupplierCode())) {
            LambdaQueryWrapper<PurchaseSupplier> supplierWrapper = new LambdaQueryWrapper<>();
            supplierWrapper.like(PurchaseSupplier::getSupplierCode, queryDTO.getSupplierCode());
            List<PurchaseSupplier> suppliers = purchaseSupplierMapper.selectList(supplierWrapper);
            supplierIds.addAll(suppliers.stream().map(PurchaseSupplier::getId).collect(Collectors.toList()));
        }

        // 根据产品编号模糊查询
        if (StringUtils.hasText(queryDTO.getProductCode())) {
            LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.like(Product::getProductCode, queryDTO.getProductCode());
            List<Product> products = productMapper.selectList(productWrapper);
            productIds.addAll(products.stream().map(Product::getProductId).collect(Collectors.toList()));
        }

        // 根据产品名称模糊查询
        if (StringUtils.hasText(queryDTO.getProductName())) {
            LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.like(Product::getProductName, queryDTO.getProductName());
            List<Product> products = productMapper.selectList(productWrapper);
            productIds.addAll(products.stream().map(Product::getProductId).collect(Collectors.toList()));
        }

        // 应用查询条件 - 使用OR逻辑组合多个条件
        boolean hasCondition = false;
        boolean hasAnyQuery = StringUtils.hasText(queryDTO.getDemandOrderNo()) ||
                             StringUtils.hasText(queryDTO.getPurchaseOrderNo()) ||
                             StringUtils.hasText(queryDTO.getSupplierCode()) ||
                             StringUtils.hasText(queryDTO.getProductCode()) ||
                             StringUtils.hasText(queryDTO.getProductName());

        if (!orderIds.isEmpty()) {
            queryWrapper.in(PurchaseReturn::getStorageId, orderIds.stream().map(String::valueOf).collect(Collectors.toList()));
            hasCondition = true;
        }

        if (!supplierIds.isEmpty()) {
            if (hasCondition) {
                queryWrapper.or().in(PurchaseReturn::getSupplierId, supplierIds);
            } else {
                queryWrapper.in(PurchaseReturn::getSupplierId, supplierIds);
                hasCondition = true;
            }
        }

        if (!productIds.isEmpty()) {
            if (hasCondition) {
                queryWrapper.or().in(PurchaseReturn::getProductId, productIds);
            } else {
                queryWrapper.in(PurchaseReturn::getProductId, productIds);
                hasCondition = true;
            }
        }

        // 如果有查询条件但没有找到匹配的关联数据，返回空结果
        if (hasAnyQuery && !hasCondition) {
            queryWrapper.eq(PurchaseReturn::getId, -1);
        }

        // 根据采购退货状态查询
        if (StringUtils.hasText(queryDTO.getReturnStatus())) {
            queryWrapper.eq(PurchaseReturn::getReturnStatus, queryDTO.getReturnStatus());
        }

        // 根据退货时间范围查询
        if (queryDTO.getReturnTimeStart() != null) {
            queryWrapper.ge(PurchaseReturn::getReturnTime, queryDTO.getReturnTimeStart());
        }
        if (queryDTO.getReturnTimeEnd() != null) {
            queryWrapper.le(PurchaseReturn::getReturnTime, queryDTO.getReturnTimeEnd());
        }

        // 按ID倒序排列
//        queryWrapper.orderByDesc(PurchaseReturn::getId);

        // 执行分页查询
        IPage<PurchaseReturn> purchaseReturnPage = this.page(page, queryWrapper);

        // 转换为VO
        IPage<PurchaseReturnVO> voPage = new Page<>();
        BeanUtils.copyProperties(purchaseReturnPage, voPage);

        List<PurchaseReturnVO> voList = purchaseReturnPage.getRecords().stream().map(returnRecord -> {
            PurchaseReturnVO vo = new PurchaseReturnVO();
            BeanUtils.copyProperties(returnRecord, vo);

            // 设置状态描述
            vo.setReturnStatusDesc(getReturnStatusDesc(returnRecord.getReturnStatus()));

            // 设置产品信息
            if (returnRecord.getProductId() != null) {
                Product product = productMapper.selectById(returnRecord.getProductId());
                if (product != null) {
                    vo.setProductCode(product.getProductCode());
                    vo.setProductName(product.getProductName());
                    vo.setSpecification(product.getSpecification());
                    vo.setCategory(product.getCategory());
                    vo.setCategoryDesc(getCategoryDesc(product.getCategory()));
                    vo.setUnitId(product.getUnitId());

                    // 设置单位信息
                    if (product.getUnitId() != null) {
                        Unit unit = unitMapper.selectById(product.getUnitId());
                        if (unit != null) {
                            vo.setUnitName(unit.getUnitName());
                        }
                    }
                }
            }

            // 设置供应商信息
            if (returnRecord.getSupplierId() != null) {
                PurchaseSupplier supplier = purchaseSupplierMapper.selectById(returnRecord.getSupplierId());
                if (supplier != null) {
                    vo.setSupplierCode(supplier.getSupplierCode());
                    vo.setSupplierName(supplier.getSupplierName());
                }
            }

            // 设置仓库信息
            if (returnRecord.getWarehouseId() != null) {
                Warehouse warehouse = warehouseMapper.selectById(returnRecord.getWarehouseId());
                if (warehouse != null) {
                    vo.setWarehouseName(warehouse.getWarehouseName());
                }
            }

            return vo;
        }).collect(Collectors.toList());

        voPage.setRecords(voList);

        return voPage;
    }

    /**
     * 新增采购退货
     */
    @Override
    public boolean addPurchaseReturn(PurchaseReturnAddDTO addDTO) {
        PurchaseReturn purchaseReturn = new PurchaseReturn();
        BeanUtils.copyProperties(addDTO, purchaseReturn);

        // 生成采购退货编号：CK + 年月日 + 随机四位数
        String returnOrderNo = generateReturnOrderNo();
        purchaseReturn.setReturnOrderNo(returnOrderNo);

        return this.save(purchaseReturn);
    }

    /**
     * 生成采购退货编号
     * 格式：CK + YYYYMMDD + 随机四位数
     */
    private String generateReturnOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());

        Random random = new Random();
        int randomNum = random.nextInt(9000) + 1000; // 生成1000-9999的随机数

        return "CK" + dateStr + randomNum;
    }

    /**
     * 获取退货状态描述
     */
    private String getReturnStatusDesc(String returnStatus) {
        if (returnStatus == null) return "";

        switch (returnStatus) {
            case "0": return "待退货";
            case "1": return "待寄出";
            case "2": return "已寄出";
            case "3": return "待收货";
            default: return "未知状态";
        }
    }

    /**
     * 获取产品分类描述
     */
    private String getCategoryDesc(Integer category) {
        if (category == null) return "";

        switch (category) {
            case 0: return "成品";
            case 1: return "半成品";
            case 2: return "残次品";
            default: return "未知分类";
        }
    }

    /**
     * 根据ID查询采购退货详情
     */
    @Override
    public PurchaseReturnVO getPurchaseReturnDetail(Integer id) {
        PurchaseReturn purchaseReturn = this.getById(id);
        if (purchaseReturn == null) {
            return null;
        }

        PurchaseReturnVO vo = new PurchaseReturnVO();
        BeanUtils.copyProperties(purchaseReturn, vo);

        // 设置状态描述
        vo.setReturnStatusDesc(getReturnStatusDesc(purchaseReturn.getReturnStatus()));

        // 设置产品信息
        if (purchaseReturn.getProductId() != null) {
            Product product = productMapper.selectById(purchaseReturn.getProductId());
            if (product != null) {
                vo.setProductCode(product.getProductCode());
                vo.setProductName(product.getProductName());
                vo.setSpecification(product.getSpecification());
                vo.setCategory(product.getCategory());
                vo.setCategoryDesc(getCategoryDesc(product.getCategory()));
                vo.setUnitId(product.getUnitId());

                // 设置单位信息
                if (product.getUnitId() != null) {
                    Unit unit = unitMapper.selectById(product.getUnitId());
                    if (unit != null) {
                        vo.setUnitName(unit.getUnitName());
                    }
                }
            }
        }

        // 设置供应商信息
        if (purchaseReturn.getSupplierId() != null) {
            PurchaseSupplier supplier = purchaseSupplierMapper.selectById(purchaseReturn.getSupplierId());
            if (supplier != null) {
                vo.setSupplierCode(supplier.getSupplierCode());
                vo.setSupplierName(supplier.getSupplierName());
            }
        }

        // 设置仓库信息
        if (purchaseReturn.getWarehouseId() != null) {
            Warehouse warehouse = warehouseMapper.selectById(purchaseReturn.getWarehouseId());
            if (warehouse != null) {
                vo.setWarehouseName(warehouse.getWarehouseName());
            }
        }

        return vo;
    }

    /**
     * 更新采购退货
     */
    @Override
    public boolean updatePurchaseReturn(PurchaseReturnAddDTO updateDTO) {
        if (updateDTO.getId() == null) {
            throw new IllegalArgumentException("更新采购退货时ID不能为空");
        }
        
        PurchaseReturn purchaseReturn = new PurchaseReturn();
        BeanUtils.copyProperties(updateDTO, purchaseReturn);
        
        return this.updateById(purchaseReturn);
    }
}




